package org.autumn.jvm;

import lombok.extern.slf4j.Slf4j;

import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.ArrayList;

/**
 * -Xmx20m -XX:+PrintGCDetails
 */
@Slf4j
public class ReferenceFive {

    private static final int _4M = 1024 * 1024 * 4;

    public static void main(String[] args) {

    }

    private static void weakReferenceTest() {
        ArrayList<WeakReference<byte[]>> weak = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            WeakReference<byte[]> data = new WeakReference<>(new byte[_4M]);
            System.out.println(data.get());
            if (i == 3){
                weak.forEach(System.out::println);
            }
            weak.add(data);
        }

        System.out.println("----------------------------");

    }

    /**
     * -Xmx20m 添加虚拟机参数
     */
    private static void outOfMemory() {
        ArrayList<byte[]> bytes = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            bytes.add(new byte[_4M]);
        }
    }


    /**
     * -Xmx20m 添加虚拟机参数
     */
    private static void softReferenceTest() {
        ArrayList<SoftReference<byte[]>> soft = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            SoftReference<byte[]> data = new SoftReference<>(new byte[_4M]);
            System.out.println(data.get());
            soft.add(data);
            System.out.println(i);
        }
        System.out.println("-----------------------------");
                        for (SoftReference<byte[]> softReference : soft) {
            System.out.println(softReference.get());
        }
    }
}
